using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour {
	
	// public varaibles
	public float travelSpeed = 100;
	
	// private variables
	private ArrayList myPath;
	private float nextWaypointDistance = 1;
	private int currentWaypoint = 0;
	private CharacterController controller;
	private EnemyControler myControler;
	
	// Use this for initialization
	void Start () {
		controller = GetComponent<CharacterController>();
		GameObject temp = GameObject.Find("ControlContainer");
		myControler = temp.GetComponent<EnemyControler>();
	}
	
	public void takePath(Vector3[] vp){
		myPath = personalisePath(vp);
	}
	
	private ArrayList personalisePath(Vector3[] path){
		
		ArrayList changablePath = new ArrayList();// = path;
		
		for(int p = 0; p < path.Length; p++){
			changablePath.Add(path[p]);
		}
		
		//ArrayList changablePath = path;
		int closestPoint = 0;
		float distanceKeeper = Vector3.Distance(transform.position, (Vector3) changablePath[0]);
		
		for(int i = 0; i < changablePath.Count; i++){
			if(Vector3.Distance(transform.position, (Vector3) changablePath[i]) < distanceKeeper){
				closestPoint = i;
			}
		}
		
		changablePath.RemoveRange(0, closestPoint);
		currentWaypoint = 0;
		return changablePath;
	}
	
	public void FixedUpdate () {
		if (myPath == null) {
			//We have no path to move after yet
			return;
		}
	
		if (currentWaypoint >= myPath.Count) {
			Debug.Log ("End Of Path Reached");
			myControler.removeEnemy(gameObject);
			return;
		}
	
		//Direction to the next waypoint
		Vector3 dir = ((Vector3) myPath[currentWaypoint] - transform.position).normalized;
		dir *= travelSpeed * Time.fixedDeltaTime;
		controller.SimpleMove (dir);
		
		 transform.LookAt((Vector3) myPath[currentWaypoint]);
		
		if (Vector3.Distance (transform.position,(Vector3) myPath[currentWaypoint]) < nextWaypointDistance) {
			currentWaypoint++;
			return;
		}
	}
	
	
	
	// Update is called once per frame
	void Update () {
	
	}
}
